package cn.com.xf.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.ConfigUtil;
import cn.com.xf.common.Constants;
import cn.com.xf.common.PinyinUtils;
import cn.com.xf.domain.TblSiteCompany;
import cn.com.xf.domain.TblSiteFeedback;
import cn.com.xf.domain.TblSiteGray;
import cn.com.xf.domain.TblSiteJob;
import cn.com.xf.domain.TblSiteNews;
import cn.com.xf.domain.TblSiteProduct;
import cn.com.xf.domain.TblSiteResume;
import cn.com.xf.domain.TblSiteSeo;
import cn.com.xf.domain.TblSiteVedio;
import cn.com.xf.domain.TblSiteWeekly;
import cn.com.xf.domain.TblSiteWeeklyArticle;
import cn.com.xf.domain.TblSiteWeeklyMap;
import cn.com.xf.service.SiteService;
import cn.com.xf.service.WeeklyService;
import cn.com.xf.utils.encode.EncrypTool;
import cn.com.xf.web.PageModel;
import cn.com.xf.web.XFMappingJacksonJsonView;
import cn.com.xf.web.form.FeedBackForm;
import cn.com.xf.web.form.JobForm;
import cn.com.xf.web.form.ResumeForm;
import cn.com.xf.web.form.SiteForm;
import cn.com.xf.web.form.VideoForm;
import cn.com.xf.web.security.UserInfo;

@Controller
@RequestMapping("/site")
public class SiteController extends AbstractBaseController {

	@Autowired
	private SiteService siteService;
	@Autowired
	private WeeklyService weeklyService;

	@RequestMapping(value = "/copy")
	public ModelAndView copy(HttpServletRequest request, HttpServletResponse response, SiteForm form) throws Exception {
		siteService.updateForCopyAllOldData(request.getContextPath());
		response.getWriter().append("Data copy success!");
		return null;
	}

	@RequestMapping
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, SiteForm form) throws Exception {
		form.setTab(Constants.TAB_SITE);
		ModelAndView mv = new ModelAndView("/site/index", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	@RequestMapping(value = "/news")
	public ModelAndView news(HttpServletRequest request, HttpServletResponse response, SiteForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/site/news", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	/**
	 * 编辑页面
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response, SiteForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/site/edit", Constants.FORM_COMMAND_KEY, form);
		form.setTab(Constants.TAB_SITE);
		String module = form.getModule().trim();
		String name = form.getName().trim();
		if (Constants.SITE_MODULE_PRODUCT.equalsIgnoreCase(module)) {
			TblSiteProduct product = siteService.selectProductByType(name);
			mv.addObject("product", product);
		}
		if (Constants.SITE_MODULE_CUSTOM.equalsIgnoreCase(module)) {
			TblSiteCompany company = siteService.selectCompanyByType(name);
			mv.addObject("company", company);
		}
		return mv;
	}

	@RequestMapping(value = "/doEdit")
	public ModelAndView doEdit(HttpServletRequest request, HttpServletResponse response, SiteForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/result", Constants.FORM_COMMAND_KEY, form);
		form.setTab(Constants.TAB_SITE);
		String module = form.getModule().trim();
		String name = form.getName().trim();
		String content = form.getContent();
		String contentEn = form.getContentEn();
		String contentBig5 = form.getContentBig5();
		if (Constants.SITE_MODULE_PRODUCT.equalsIgnoreCase(module)) {
			siteService.updateProductByType(name, content, contentEn, contentBig5);
		}
		if (Constants.SITE_MODULE_CUSTOM.equalsIgnoreCase(module)) {
			siteService.updateCompanyByType(name, content, contentEn, contentBig5);
		}
		mv.addObject("status", "SUCCESS");
		return mv;
	}

	@RequestMapping(value = "/newsAdd")
	public ModelAndView news_add(HttpServletRequest request, HttpServletResponse response, SiteForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/news_add", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	@RequestMapping(value = "/videoAdd")
	public ModelAndView video_add(HttpServletRequest request, HttpServletResponse response, VideoForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/video_add", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	@RequestMapping(value = "/doNewsAdd")
	public ModelAndView news_doAdd(HttpServletRequest request, HttpServletResponse response, @Valid SiteForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/site/news_result", Constants.FORM_COMMAND_KEY, form);
		MultipartFile file = form.getImgFile();
		TblSiteNews news = form.copyTo();
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if (!file.isEmpty()) {
			// 存储到文件
			// String prepath = servletContext.getRealPath("/");
			String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "_"
					+ file.getOriginalFilename();
			// String savePath = prepath + Constants.UPLOAD_PATH_IMAGE;
			// String relativePath = Constants.UPLOAD_PATH_IMAGE + "/" +
			// newFileName;
			// File saveFile = new File(savePath, newFileName);
			// file.transferTo(saveFile);
			// 存储一份到site网站
			// String siteFilePathRoot =
			// ConfigUtil.getValue("uploadImageSavePath");
			// File siteFile = new File(siteFilePathRoot, newFileName);
			// file.transferTo(siteFile);
			news.setPicture(newFileName);
			siteService.insertNews(news);
			mv.addObject("status", "success");

			// 存储到绝对目录
			String absoluteFilePath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
					+ Constants.ABSOLUTE_ROOT_IMAGE_PATH;
			File fileFile = new File(absoluteFilePath);
			if (!fileFile.exists()) {
				fileFile.mkdirs();
			}
			File absoluteFileFile = new File(absoluteFilePath, newFileName);
			file.transferTo(absoluteFileFile);
			// saveUrl = request.getContextPath() + "/filextra/" + newFileName;

			return mv;

		}

		siteService.insertNews(news);
		mv.addObject("status", "success");
		return mv;
	}

	/**
	 * 保存视频 旧版作废
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doVideoAdd2")
	public ModelAndView video_doAdd2(HttpServletRequest request, HttpServletResponse response, @Valid VideoForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/site/video_result", Constants.FORM_COMMAND_KEY, form);
		TblSiteVedio video = new TblSiteVedio();
		video.setDescribe(form.getVideoDesc());
		video.setName(form.getVideoTitle());
		video.setAdduser(form.getPublicMan());
		video.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(form.getPublicTime()));
		video.setDateStr(form.getPublicTime());
		MultipartFile file = form.getMultipartFile();
		String fileName = file.getOriginalFilename();
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		HashMap<String, String> extMap = new HashMap<String, String>();
		String exts = "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb";
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			mv.addObject("msg", "添加失败:必填内容不能为空");
			return mv;
		}
		if (!file.isEmpty()) {
			if (Arrays.<String> asList(exts.split(",")).contains(fileExt)) {
				String prepath = servletContext.getRealPath("/");
				String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "_"
						+ file.getOriginalFilename();
				String savePath = prepath + Constants.UPLOAD_PATH_MEDIA;
				String relativePath = Constants.UPLOAD_PATH_MEDIA + "/" + newFileName;
				File saveFile = new File(savePath, newFileName);
				file.transferTo(saveFile);
				video.setDir(relativePath);
				siteService.insertVideo(video);
				mv.addObject("status", "success");
				mv.addObject("msg", "添加成功");
				return mv;
			} else {
				mv.addObject("status", "error");
				mv.addObject("msg", "添加失败:上传文件扩展名是不允许的扩展名。只允许" + exts + "格式。");
				return mv;
			}
		}
		mv.addObject("status", "error");
		mv.addObject("msg", "添加失败:文件不能为空!");
		return mv;
	}

	@RequestMapping(value = "/doVideoAdd")
	public ModelAndView video_doAdd(HttpServletRequest request, HttpServletResponse response, @Valid VideoForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/site/video_result", Constants.FORM_COMMAND_KEY, form);
		MultipartFile imgFile = form.getImgFile();
		// 1.错误检查
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		// 2.提取临时文件中的文件
		// 2.1空值检查
		String tempFileId = form.getTempFileId();
		if (StringUtils.isBlank(form.getTempFileId())) {
			return null;
		}
		// 2.2获取临时文件列表
		TblSiteVedio video = new TblSiteVedio();
		String formalFileName = "";
		String tempFilesPath = servletContext.getRealPath("/") + Constants.UPLOAD_PATH_TEMP;
		File dir = new File(tempFilesPath);
		File file[] = dir.listFiles();
		// 2.3转存到正式的目录
		for (File f : file) {
			if (f.isFile()) {
				String allname = f.getName();
				if (allname.contains(Constants.UPLOAD_TEMP_SPILT)) {
					String name = allname.split(Constants.UPLOAD_TEMP_SPILT)[0];
					if (tempFileId.equalsIgnoreCase(name)) {
						// 找打了临时文件存储到正式目录
						// String formalFilePath =
						// servletContext.getRealPath("/") +
						// Constants.UPLOAD_PATH_MEDIA;
						formalFileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "_"
								+ PinyinUtils.converterToSpell(allname.split(Constants.UPLOAD_TEMP_SPILT)[1]);
						// File formalFile = new File(formalFilePath,
						// formalFileName);
						// 拷贝文件到正式目录
						// fileChannelCopy(f, formalFile);
						// 拷贝到网站的的目录下
						String absoluteFlvPath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
								+ Constants.ABSOLUTE_ROOT_FLV_PATH;
						File flvFile = new File(absoluteFlvPath);
						if (!flvFile.exists()) {
							flvFile.mkdirs();
						}
						File siteFormalFile = new File(absoluteFlvPath, formalFileName);
						fileChannelCopy(f, siteFormalFile);
					}
				}
			}
		}
		if (StringUtils.isBlank(formalFileName)) {
			return null;
		}

		if (!imgFile.isEmpty()) {
			// 存储到文件
			// String prepath = servletContext.getRealPath("/");
			String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "_"
					+ imgFile.getOriginalFilename();
			// String savePath = prepath + Constants.UPLOAD_PATH_IMAGE;
			// String relativePath = Constants.UPLOAD_PATH_IMAGE + "/" +
			// newFileName;
			// File saveFile = new File(savePath, newFileName);
			// file.transferTo(saveFile);
			// 存储一份到site网站
			// String siteFilePathRoot =
			// ConfigUtil.getValue("uploadImageSavePath");
			// File siteFile = new File(siteFilePathRoot, newFileName);
			// file.transferTo(siteFile);
			video.setPicture(newFileName);

			// 存储到绝对目录
			String absoluteFilePath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
					+ Constants.ABSOLUTE_ROOT_IMAGE_PATH;
			File fileFile = new File(absoluteFilePath);
			if (!fileFile.exists()) {
				fileFile.mkdirs();
			}
			File absoluteFileFile = new File(absoluteFilePath, newFileName);
			imgFile.transferTo(absoluteFileFile);
		}

		// 3.存储
		video.setDescribe(form.getVideoDesc());
		video.setName(form.getVideoTitle());
		video.setDir(formalFileName);
		video.setDateStr(form.getPublicTime());
		siteService.insertVideo(video);
		mv.addObject("status", "success");
		return mv;
	}

	@RequestMapping(value = "/newsList")
	public ModelAndView news_list(HttpServletRequest request, HttpServletResponse response, SiteForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/news_list", Constants.FORM_COMMAND_KEY, form);
		// 1.模糊搜索关键字
		String searchField = null;
		String searchValue = null;
		if (StringUtils.isNotBlank(form.getTitle())) {
			searchField = "title";
			searchValue = form.getTitle().trim();
		}
		String isimportant = null;
		String istop = null;
		String isShow = null;
		String type = Constants.NEWS_GROUP_GONGSI;
		if (StringUtils.isNotBlank(form.getIsimportant())) {
			isimportant = form.getIsimportant();
		}
		if (StringUtils.isNotBlank(form.getIstop())) {
			istop = form.getIstop();
		}
		if (StringUtils.isNotBlank(form.getGroup())) {
			type = form.getGroup();
		}
		if (StringUtils.isNotBlank(form.getIsShow())) {
			isShow = form.getIsShow();
		}

		form.setIsimportant(isimportant);
		form.setIstop(istop);
		form.setType(type);
		form.setIsShow(isShow);
		// 2.总记录数
		int count = siteService.selectNewsCount(searchField, searchValue, isimportant, istop, type, isShow);
		if (count == 0) {
			return mv;
		}

		// 3.分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();

		// 4.排序规则
		String orderByField = "PUBLIC_TIME";
		String orderByMode = "DESC";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("title".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "title";
			}
			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}

		// 5.查询
		List<TblSiteNews> list = siteService.selectNews(begin, pageSize, searchField, searchValue, orderByField,
				orderByMode, isimportant, istop, type, isShow);
		mv.addObject("list", list);
		return mv;
	}

	@RequestMapping(value = "/detail")
	public ModelAndView news_detail(HttpServletRequest request, HttpServletResponse response, SiteForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/news_detail", Constants.FORM_COMMAND_KEY, form);
		int id = Integer.valueOf(EncrypTool.dencode(form.getId()));
		TblSiteNews news = siteService.selectNewsById(id);
		mv.addObject("news", news);
		return mv;
	}

	@RequestMapping(value = "/newsEdit")
	public ModelAndView news_edit(HttpServletRequest request, HttpServletResponse response, SiteForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/news_edit", Constants.FORM_COMMAND_KEY, form);
		int id = Integer.valueOf(EncrypTool.dencode(form.getId()));
		TblSiteNews news = siteService.selectNewsById(id);
		mv.addObject("news", news);
		return mv;
	}

	@RequestMapping(value = "/doNewsEdit")
	public ModelAndView news_doEdit(HttpServletRequest request, HttpServletResponse response, @Valid SiteForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/site/news_result", Constants.FORM_COMMAND_KEY, form);
		MultipartFile file = form.getImgFile();
		TblSiteNews news = form.copyTo();
		news.setId(new BigDecimal(form.getId()));
		news.setUpdatetime(new Date());// 设置更新时间
		UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		news.setUpdateuser(user.getName());// 设置更新人
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if (file.isEmpty()) {
			news.setPicture(siteService.selectNewsById(Integer.valueOf(form.getId())).getPicture());
			siteService.updateNews(news);
			mv.addObject("status", "success");
			return mv;
		}
		// String prepath = servletContext.getRealPath("/");
		String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "_"
				+ file.getOriginalFilename();
		// String savePath = prepath + Constants.UPLOAD_PATH_IMAGE;
		// String relativePath = Constants.UPLOAD_PATH_IMAGE + "/" +
		// newFileName;
		// File saveFile = new File(savePath, newFileName);
		// file.transferTo(saveFile);

		// 2.存储到指定的服务器地址
		// String uploadSavePath = ConfigUtil.getValue("uploadImageSavePath");
		// File siteSaveFile = new File(uploadSavePath, newFileName);
		// file.transferTo(siteSaveFile);

		// 存储到绝对目录
		String absoluteFilePath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
				+ Constants.ABSOLUTE_ROOT_IMAGE_PATH;
		File fileFile = new File(absoluteFilePath);
		if (!fileFile.exists()) {
			fileFile.mkdirs();
		}
		File absoluteFileFile = new File(absoluteFilePath, newFileName);
		file.transferTo(absoluteFileFile);

		news.setPicture(newFileName);
		siteService.updateNews(news);
		mv.addObject("status", "success");
		return mv;
	}

	@RequestMapping(value = "/newsDelete")
	public ModelAndView news_delete(HttpServletRequest request, HttpServletResponse response, SiteForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/news_result", Constants.FORM_COMMAND_KEY, form);
		BigDecimal id = new BigDecimal(EncrypTool.dencode(form.getId()));
		siteService.deleteNews(id);
		mv.addObject("status", "success");
		return mv;
	}

	@RequestMapping(value = "/videoList")
	public ModelAndView videoList(HttpServletRequest request, HttpServletResponse response, VideoForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/video_list", Constants.FORM_COMMAND_KEY, form);
		// 3.分页信息
		int count = siteService.selectVideoCount();
		if (count == 0)
			return mv;
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		String orderByField = "ADDTIME";
		String orderByMode = "DESC";

		List<TblSiteVedio> list = siteService.selectVideos(begin, pageSize, null, null);
		mv.addObject("list", list);
		return mv;
	}

	@RequestMapping(value = "/deleteVideo")
	public ModelAndView video_delete(HttpServletRequest request, HttpServletResponse response, VideoForm form)
			throws Exception {
		String id = form.getId();
		String videoId = EncrypTool.dencode(id);
		Map<String, String> map = new HashMap<String, String>();
		int result = siteService.deleteVideo(Integer.valueOf(videoId));
		if (result == -1) {
			map.put("status", "FAILD");
		} else if (result == 1) {
			map.put("status", "SUCCESS");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;
	}

	@RequestMapping(value = "/videoEdit")
	public ModelAndView video_edit(HttpServletRequest request, HttpServletResponse response, VideoForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/video_edit", Constants.FORM_COMMAND_KEY, form);
		String id = form.getId();
		String videoId = EncrypTool.dencode(id);
		TblSiteVedio video = siteService.selectVideoById(Integer.valueOf(videoId));
		mv.addObject("video", video);
		return mv;
	}

	@RequestMapping(value = "/doVideoEdit")
	public ModelAndView video_doEdit(HttpServletRequest request, HttpServletResponse response, @Valid VideoForm form,
			BindingResult result) throws Exception {
		/*
		 * ModelAndView mv = new ModelAndView("/site/video_result",
		 * Constants.FORM_COMMAND_KEY, form); String id = form.getId(); String
		 * videoId = EncrypTool.dencode(id); TblSiteVedio video =
		 * siteService.selectVideoById(Integer.valueOf(videoId));
		 * video.setDescribe(form.getVideoDesc());
		 * video.setName(form.getVideoTitle());
		 * video.setAdduser(form.getPublicMan()); video.setAddtime(new
		 * SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(form.getPublicTime()));
		 * video.setDateStr(form.getPublicTime()); UserInfo user = (UserInfo)
		 * SecurityContextHolder
		 * .getContext().getAuthentication().getPrincipal();
		 * video.setUpdatetime(new Date());// 设置更新时间
		 * video.setUpdateuser(user.getName());// 设置更新人 MultipartFile file =
		 * form.getMultipartFile(); List<ObjectError> errorList = null; if
		 * (result.hasErrors()) { errorList = result.getAllErrors(); //
		 * 将错误信息Json化 String errorJson = errorToJson(errorList);
		 * mv.addObject("errorJson", errorJson); mv.addObject("msg",
		 * "更新失败:必填内容不能为空"); return mv; } if (file.isEmpty()) {
		 * siteService.updateVideo(video); mv.addObject("status", "success");
		 * mv.addObject("msg", "更新成功"); return mv; }
		 * 
		 * String prepath = servletContext.getRealPath("/"); String newFileName
		 * = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "_"
		 * + file.getOriginalFilename(); String savePath = prepath +
		 * Constants.UPLOAD_PATH_MEDIA; String relativePath =
		 * Constants.UPLOAD_PATH_MEDIA + "/" + newFileName; File saveFile = new
		 * File(savePath, newFileName); file.transferTo(saveFile);
		 * video.setDir(relativePath); siteService.updateVideo(video);
		 * mv.addObject("status", "success"); return mv;
		 */

		ModelAndView mv = new ModelAndView("/site/video_result", Constants.FORM_COMMAND_KEY, form);
		UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		// 1.错误检查
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		String videoId = EncrypTool.dencode(form.getId() + "");
		TblSiteVedio video = siteService.selectVideoById(Integer.valueOf(videoId));
		if (null == video) {
			return null;
		}
		// 2.提取临时文件中的文件
		// 2.1空值检查
		String tempFileId = form.getTempFileId();
		// 软件没有修改，直接保存其他字段
		if (StringUtils.isNotBlank(form.getTempFileId())) {
			// 2.2获取临时文件列表
			String formalFileName = "";
			String tempFilesPath = servletContext.getRealPath("/") + Constants.UPLOAD_PATH_TEMP;
			File dir = new File(tempFilesPath);
			File file[] = dir.listFiles();
			// 2.3转存到正式的目录
			for (File f : file) {
				if (f.isFile()) {
					String allname = f.getName();
					if (allname.contains(Constants.UPLOAD_TEMP_SPILT)) {
						String name = allname.split(Constants.UPLOAD_TEMP_SPILT)[0];
						if (tempFileId.equalsIgnoreCase(name)) {
							// 找打了临时文件存储到正式目录
							String formalFilePath = servletContext.getRealPath("/") + Constants.UPLOAD_PATH_MEDIA;
							formalFileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "_"
									+ PinyinUtils.converterToSpell(allname.split(Constants.UPLOAD_TEMP_SPILT)[1]);
							File formalFile = new File(formalFilePath, formalFileName);
							// 拷贝文件到正式目录
							fileChannelCopy(f, formalFile);
							// 拷贝到网站的的目录下
							String siteFormalFilePath = ConfigUtil.getValue("siteVideoRootPath");
							File siteFormalFile = new File(siteFormalFilePath, formalFileName);
							fileChannelCopy(f, siteFormalFile);
						}
					}
				}
			}
			if (StringUtils.isBlank(formalFileName)) {
				return null;
			}
			video.setDir(formalFileName);
		}

		// 3.存储
		video.setDateStr(form.getPublicTime());
		video.setDescribe(form.getVideoDesc());
		video.setName(form.getVideoTitle());
		video.setUpdatetime(new Date());
		video.setUpdateuser(user.getName());
		siteService.updateVideo(video);
		mv.addObject("status", "SUCCESS");
		mv.addObject("msg", "更新成功");
		return mv;

	}

	@RequestMapping(value = "/videoDetail")
	public ModelAndView video_detail(HttpServletRequest request, HttpServletResponse response, VideoForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/video_detail", Constants.FORM_COMMAND_KEY, form);
		String id = form.getId();
		String videoId = EncrypTool.dencode(id);
		TblSiteVedio video = siteService.selectVideoById(Integer.valueOf(videoId));
		mv.addObject("video", video);
		return mv;
	}

	@RequestMapping(value = "/jobAdd")
	public ModelAndView jobAdd(HttpServletRequest request, HttpServletResponse response, JobForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/site/job_add", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}

	@RequestMapping(value = "/doJobAdd")
	public ModelAndView doJobAdd(HttpServletRequest request, HttpServletResponse response, @Valid JobForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/site/job_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			mv.addObject("msg", "添加失败:必填内容不能为空");
			return mv;
		}
		TblSiteJob job = form.copyTo();
		siteService.insertJob(job);
		mv.addObject("status", "success");
		mv.addObject("msg", "添加成功");
		return mv;

	}

	@RequestMapping(value = "/jobList")
	public ModelAndView jobList(HttpServletRequest request, HttpServletResponse response, JobForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/job_list", Constants.FORM_COMMAND_KEY, form);
		// 3.分页信息
		int count = siteService.selectJobCount();
		if (count == 0)
			return mv;
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();

		List<TblSiteJob> list = siteService.selectJob(begin, pageSize);
		mv.addObject("list", list);
		return mv;
	}

	@RequestMapping(value = "/deleteJob")
	public ModelAndView job_delete(HttpServletRequest request, HttpServletResponse response, VideoForm form)
			throws Exception {
		String id = form.getId();
		String jobId = EncrypTool.dencode(id);
		Map<String, String> map = new HashMap<String, String>();
		int result = siteService.deleteJob(Integer.valueOf(jobId));
		if (result == -1) {
			map.put("status", "FAILD");
		} else if (result == 1) {
			map.put("status", "SUCCESS");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;
	}

	@RequestMapping(value = "/jobEdit")
	public ModelAndView job_edit(HttpServletRequest request, HttpServletResponse response, JobForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/job_edit", Constants.FORM_COMMAND_KEY, form);
		String id = form.getId();
		String jobId = EncrypTool.dencode(id);
		TblSiteJob job = siteService.selectJobById(Integer.valueOf(jobId));
		mv.addObject("job", job);
		return mv;
	}

	@RequestMapping(value = "/doJobEdit")
	public ModelAndView doJobEdit(HttpServletRequest request, HttpServletResponse response, @Valid JobForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/site/job_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			mv.addObject("msg", "更新失败:必填内容不能为空");
			return mv;
		}
		TblSiteJob job = form.copyTo();
		String id = form.getId();
		String jobId = EncrypTool.dencode(id);
		job.setId(new BigDecimal(jobId));
		job.setJob("JOB");
		job.setUpdatetime(new Date());// 更新时间
		UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		job.setUpdateuser(user.getName());// 更新人
		siteService.updateJob(job);
		mv.addObject("status", "success");
		mv.addObject("msg", "更新成功");
		return mv;
	}

	@RequestMapping(value = "/feedbackList")
	public ModelAndView feedback_list(HttpServletRequest request, HttpServletResponse response, FeedBackForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/feedback_list", Constants.FORM_COMMAND_KEY, form);
		// 1.模糊搜索关键字
		String name = null;
		String content = null;
		String orderId = null;
		if (StringUtils.isNotBlank(form.getContent())) {
			content = form.getContent().trim();
		}
		if (StringUtils.isNotBlank(form.getOrderId())) {
			orderId = form.getOrderId();
		}
		if (StringUtils.isNotBlank(form.getName())) {
			name = form.getName();
		}
		// 2.总记录数
		int count = siteService.selectFeedbackCount(name, orderId, content);
		if (count == 0) {
			return mv;
		}

		// 3.分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();

		// 4.排序规则
		String orderByField = "ADDTIME";
		String orderByMode = "DESC";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("orderId".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "orderId";
			}
			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}

		// 5.查询
		List<TblSiteFeedback> list = siteService.selectFeedBack(begin, pageSize, orderByField, orderByMode, name,
				orderId, content);
		mv.addObject("list", list);
		return mv;
	}

	@RequestMapping(value = "/feedbackDetail")
	public ModelAndView feedback_detail(HttpServletRequest request, HttpServletResponse response, FeedBackForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/feedback_detail", Constants.FORM_COMMAND_KEY, form);
		int id = Integer.valueOf(EncrypTool.dencode(form.getId()));
		TblSiteFeedback feedback = siteService.selectFeedbackById(id);
		mv.addObject("feedback", feedback);
		return mv;
	}

	/**
	 * 页面seo列表
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/seo/list")
	public ModelAndView seoList(HttpServletRequest request, HttpServletResponse response, SiteForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/seo_list", Constants.FORM_COMMAND_KEY, form);
		List<TblSiteSeo> list = siteService.selectSiteSeoList();
		mv.addObject("list", list);
		return mv;
	}

	/**
	 * seo编辑
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/seo/edit")
	public ModelAndView seoEdit(HttpServletRequest request, HttpServletResponse response, SiteForm form)
			throws Exception {
		String id = Integer.valueOf(EncrypTool.dencode(form.getId())) + "";
		ModelAndView mv = new ModelAndView("/site/seo_edit", Constants.FORM_COMMAND_KEY, form);
		TblSiteSeo seo = siteService.selectSiteSeoById(id);
		mv.addObject("seo", seo);
		return mv;
	}

	/**
	 * seo编辑 执行
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/seo/doEdit")
	public ModelAndView seoDoEdit(HttpServletRequest request, HttpServletResponse response, SiteForm form)
			throws Exception {
		String id = Integer.valueOf(EncrypTool.dencode(form.getId())) + "";
		ModelAndView mv = new ModelAndView("/site/seo_result", Constants.FORM_COMMAND_KEY, form);
		int result = siteService.updateSiteSeo(id, form);
		if (result > -1) {
			mv.addObject("status", "SUCCESS");
			mv.addObject("msg", "更新成功");
		} else {
			mv.addObject("status", "faild");
			mv.addObject("msg", "更新失败");
		}
		return mv;
	}

	@RequestMapping(value = "/siteGray")
	public ModelAndView siteGray(HttpServletRequest request, HttpServletResponse response, SiteForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/site_gray", Constants.FORM_COMMAND_KEY, form);
		TblSiteGray siteGray = siteService.selectSiteGray();
		form.setGrayType(siteGray.getType());
		return mv;
	}

	@RequestMapping(value = "/updateSiteGray")
	public ModelAndView updateSiteGray(HttpServletRequest request, HttpServletResponse response, SiteForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/site_gray", Constants.FORM_COMMAND_KEY, form);
		TblSiteGray siteGray = new TblSiteGray();
		siteGray.setId("1");
		siteGray.setType(form.getGrayType());
		siteService.updateSiteGray(siteGray);
		return mv;
	}

	/**
	 * 管理简历
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/resumeList")
	public ModelAndView resume_list(HttpServletRequest request, HttpServletResponse response, ResumeForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/site/resume_list", Constants.FORM_COMMAND_KEY, form);
		List<TblSiteJob> jobList = siteService.selectJobs();
		mv.addObject("jobList", jobList);
		String jobName = null;
		String createDateBegin = form.getCreateDateBegin();
		String createDateEnd = form.getCreateDateEnd();
		if (StringUtils.isNotBlank(form.getJobName())) {
			jobName = form.getJobName();
		}
		form.setJobName(jobName);
		int count = siteService.selectResumeCount(jobName, createDateBegin, createDateEnd);
		if (count == 0) {
			return mv;
		}
		// 分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();

		// 排序规则
		String orderByField = "ADDTIME";
		String orderByMode = "DESC";

		// 查询
		List<TblSiteResume> list = siteService.selectResume(begin, pageSize, orderByField, orderByMode, jobName,
				createDateBegin, createDateEnd);
		mv.addObject("list", list);
		return mv;
	}

	@RequestMapping(value = "/deleteResume")
	public ModelAndView resume_delete(HttpServletRequest request, HttpServletResponse response, JobForm form)
			throws Exception {
		String id = form.getId();
		String resumeId = EncrypTool.dencode(id);
		Map<String, String> map = new HashMap<String, String>();
		int result = siteService.deleteResumeById(resumeId);
		if (result == -1) {
			map.put("status", "FAILD");
		} else if (result == 1) {
			map.put("status", "SUCCESS");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;
	}

	/**
	 * 
	 * @param s源文件
	 * @param t目标文件
	 */
	private void fileChannelCopy(File s, File t) {
		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			fi = new FileInputStream(s);
			fo = new FileOutputStream(t);
			in = fi.getChannel();// 得到对应的文件通道
			out = fo.getChannel();// 得到对应的文件通道
			in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fi.close();
				in.close();
				fo.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@RequestMapping(value = "/weeklyAdd")
	public ModelAndView weeklyAdd(HttpServletRequest request, HttpServletResponse response, SiteForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/site/weekly_add", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}
	
	@RequestMapping(value="/doWeeklyAdd")
	public ModelAndView doWeeklyAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("/site/weekly_result");

		boolean result = weeklyService.insertWeekly(request);
		if (result) {
			mv.addObject("status", "SUCCESS");
			mv.addObject("msg", "添加成功");
		} else {
			mv.addObject("msg", "添加失败");
		}
		return mv;
	}
	
	@RequestMapping(value="/doWeeklyDelete")
	public ModelAndView doWeeklyDelete(HttpServletRequest request, HttpServletResponse response, SiteForm form) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		BigDecimal id = new BigDecimal(EncrypTool.dencode(form.getWeeklyId()));
		weeklyService.deleteWeekly(id);
		map.put("status", "SUCCESS");
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;
	}
	
	@RequestMapping(value = "/weeklyList")
	public ModelAndView weeklyList(HttpServletRequest request, HttpServletResponse response, SiteForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/site/weekly_list", Constants.FORM_COMMAND_KEY, form);
		// 3.分页信息
		int count = weeklyService.selectWeeklyCount();
		if (count == 0)
			return mv;
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();

		List<TblSiteWeekly> list = weeklyService.selectWeekly(begin, pageSize);
		mv.addObject("list", list);
		return mv;
	}
}
